const express = require('express')
const router = express.Router()
const reviewService = require('services/review')
const passport = require('api/passport')

router.get('/:id', async (req, res, next) => {
  try {
    res.json(await reviewService.getReview(req.params.id))
  } catch (e) {
    next(e)
  }
})

router.put('/:id', passport.auth, async (req, res, next) => {
  try {
    let data = req.body
    let reviewId = req.params.id
    if (!data.houseId) {
      return next({message: '空间不存在'})
    }
    if (!data.content) {
      return next({message: '请填写评论内容'})
    }
    if (data.content.length > 500) {
      return next({message: '评论长度请勿超过500字'})
    }
    const review = await reviewService.getReview(reviewId)
    if (review.user.id != req.user.id) {
      return next({message: '没有操作权限'})
    }
    if (data.houseId != review.houseId) {
      return next({message: '空间不匹配'})
    }
    let reviewData = {
      pics: data.pics.join(','),
      content: data.content,
      houseId: data.houseId,
      status: 1
    }
    const id = await reviewService.update(req.params.id, reviewData)
    res.json({id})
  } catch (e) {
    next(e)
  }
})

router.post('/', passport.auth, async (req, res, next) => {
  try {
    let data = req.body
    if (!data.houseId) {
      return next({message: '空间不存在'})
    }
    if (!data.content) {
      return next({message: '请填写评论内容'})
    }
    if (data.content.length > 500) {
      return next({message: '评论长度请勿超过500字'})
    }
    let review = {
      userId: req.user.id,
      pics: data.pics.join(','),
      content: data.content,
      houseId: data.houseId
    }
    const id = await reviewService.create(review)
    res.json({id})
  } catch (e) {
    next(e)
  }
})

module.exports = router